package com.xintonghua.bussiness.api.manager;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.xintonghua.bussiness.MyAppLication;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.bean.Auth;
import com.xintonghua.bussiness.util.MyUtils;


/**
 *
 */
public class AuthManager {
    private static Auth mAuth = new Auth();
    private static final String keys = "auth_info";

    public static void destroy(Context context) throws Exception {
        mAuth = new Auth();
        MyUtils.saveSp(context, context.getString(R.string.sp_setting), keys, "");
    }

    public static Auth geteAuth() {
        return geteAuth(MyAppLication.getInstance());
    }

    public static Auth geteAuth(Context context) {
//        Auth auth_;
//        if (mAuth==null){
        return getCacheAuth(context);
//        }else {
//            auth_= mAuth;
//        }
        //  return auth_;
    }


    public static int getId(Context context) {
        return geteAuth(context) == null ? 0 : ((0 == geteAuth(context).getId()) ? 0 : geteAuth(context).getId());
    }

    public static int getId() {
        return getId(MyAppLication.getInstance());
    }

    private static Auth getCacheAuth(Context context) {
        try {
            String auth = MyUtils.getSp(context, context.getString(R.string.sp_setting), keys);
            if (!TextUtils.isEmpty(auth)) {
                return mAuth = JSONObject.parseObject(auth, Auth.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public static void cacheAuth(Context context, Auth auth) {
        synchronized (mAuth) {
            mAuth = auth;
        }
        MyUtils.saveSp(context, context.getString(R.string.sp_setting), keys, JSONObject.toJSONString(auth));
    }

}
